const Base = require('./base.js');

module.exports = class extends Base {
    /**
     * 用户登陆成功返回用户的userId以API访问的Token
     * @returns {Promise<void>}
     * 返回数据格式
     * {
     *   "data": {
     *      "userId": "5a7d428d3d1e0dc66e596e39",
     *      "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiNWE3ZDQyOGQzZDFlMGRjNjZlNTk2ZTM5IiwiaWF0IjoxNTE4MTU4NDc3LCJleHAiOjE1MTg3NjMyNzd9.xBBBCEihuOK-_g-pdkz4S8j10zat8ekxqh6lD4tR1oo"
     *   },
     *  "code": 1
     * }
     */
    async loginAction() {

        // console.log(this.ctx.state.jwtOptions);

        this.ctx.assert(this.ctx.state.jwtOptions, 401, '中间件“think-jwt”配置错误!');

        if (this.isPost) {
            // const post = JSON.parse(this.post);
            const post = this.post();

            // console.log(post);

            const username = post.username;
            const password = think.md5(post.password);

            let user = await this.mongoose('User', {}, 'admin').findOne({
                username: username,
                password: password,
                // status: 1
            }).exec();

            // console.log(user);

            if (user) {
                // if (user && user.status) {
                let data = {};

                data.userId = user.id;

                // const jwtOptions= {
                //     secret: 'your secret key',
                //     passthrough: true,
                //     expiresIn: '7 days'
                // };

                //通过中间件注入的配置信息
                const jwtOptions = this.ctx.state.jwtOptions;
                //读取密钥
                const secret = jwtOptions['secret'];
                const jwt = require('jsonwebtoken');
                //https://www.npmjs.com/package/jsonwebtoken
                // data.token = jwt.sign({
                //     data: user.id,
                //     // 设置 token 过期时间
                //     exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 30), // 60 seconds * 60 minutes = 1 hour
                // }, secret);

                data.token = jwt.sign({
                    data: user.id
                }, secret, {expiresIn: jwtOptions['expiresIn'] || '7 days'});

                //授权验证通过之后，API可以通过以下代码获取token的信息
                const userId = this.ctx.state.user;//Auth操作在设置token的时候设置了 userId值
                console.log(userId);

                // // sign with RSA SHA256
                // var cert = fs.readFileSync('private.key');  // get private key
                // var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});


                think.logger.debug(data);
                this.success(data, '登录成功');
            } else {
                this.ctx.throw(401, 'Login Error');
            }

        } else {
            this.ctx.throw(401, 'Login Error');
        }
    }

    /**
     * 用户注册，如果注册成功返回用户的userId以API访问的Token
     * @returns {Promise<void>}
     * 返回数据格式
     * {
     *   "data": {
     *      "userId": "5a7d428d3d1e0dc66e596e39",
     *      "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiNWE3ZDQyOGQzZDFlMGRjNjZlNTk2ZTM5IiwiaWF0IjoxNTE4MTU4NDc3LCJleHAiOjE1MTg3NjMyNzd9.xBBBCEihuOK-_g-pdkz4S8j10zat8ekxqh6lD4tR1oo"
     *   },
     *  "code": 1
     * }
     */
    async registerAction() {
        if (this.isPost) {
            // const post = JSON.parse(this.post);
            const post = this.post();

            const mobile = post.mobile;
            const username = post.username;
            const password = think.md5(post.password);
            const email = post.email;

            const User = this.mongoose('User', {}, 'admin');
            let user = await User.create({
                username: username,
                password: password,
                status: 1,
                mobile: mobile,
                email: email
            });

            // if (user && user.status) {
            if (user) {

                let data = {};

                data.userId = user.id;
                //读取密钥
                const jwtOptions = this.ctx.state.jwtOptions;
                const secret = jwtOptions['secret'];
                const jwt = require('jsonwebtoken');
                //https://www.npmjs.com/package/jsonwebtoken

                data.token = jwt.sign({
                    data: user.id
                }, secret, {expiresIn: jwtOptions['expiresIn'] || '7 days'});

                //授权验证通过之后，API可以通过以下代码获取token的信息
                //const userId = this.ctx.state.user.data;//Auth操作在设置token的时候设置了 userId值

                think.logger.info(data);
                this.success(data);
            } else {
                this.ctx.throw(401, 'Register Error');
            }

        } else {
            this.ctx.throw(401, 'Register Error');
        }
    }
};
